package com.childenglish.controller;

import com.childenglish.entity.SysUser;
import com.childenglish.mapper.SysUserMapper;
import com.childenglish.mapper.SysRoleMapper;
import com.childenglish.utils.DataEncryptionUtils;
import com.childenglish.utils.PasswordEncoderUtil;
import com.childenglish.utils.R;
import com.childenglish.utils.SecurityAuditLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.childenglish.utils.UserDataHelper;
import com.childenglish.utils.ValidationPatterns;
import com.childenglish.mapper.SysRolePermissionMapper;
import com.childenglish.entity.SysRolePermission;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.Date;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
public class AdminController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private com.childenglish.service.FileStorageService fileStorageService;

    @Autowired
    private com.childenglish.service.OnlineUserService onlineUserService;

    @Autowired
    private com.childenglish.service.NotificationService notificationService;

    @Autowired
    private com.childenglish.mapper.FileInfoMapper fileInfoMapper;

    // 权限映射表 - 与你的数据库权限数据保持一致
    private static final Map<String, String> PERMISSION_NAME_MAP = new HashMap<>();
    static {
        // 系统管理权限
        PERMISSION_NAME_MAP.put("system:user:view", "查看用户");
        PERMISSION_NAME_MAP.put("system:user:edit", "编辑用户");
        PERMISSION_NAME_MAP.put("system:user:delete", "删除用户");
        PERMISSION_NAME_MAP.put("system:role:view", "查看角色");
        PERMISSION_NAME_MAP.put("system:role:edit", "编辑角色");
        PERMISSION_NAME_MAP.put("system:role:delete", "删除角色");
        PERMISSION_NAME_MAP.put("system:permission:view", "查看权限");
        PERMISSION_NAME_MAP.put("system:permission:edit", "编辑权限");

        // 学习功能权限
        PERMISSION_NAME_MAP.put("learning:listening:view", "听力学习");
        PERMISSION_NAME_MAP.put("learning:reading:view", "绘本阅读");
        PERMISSION_NAME_MAP.put("learning:game:view", "游戏学习");

        // 家长功能权限
        PERMISSION_NAME_MAP.put("parent:child:view", "查看孩子");
        PERMISSION_NAME_MAP.put("parent:progress:view", "查看进度");
        PERMISSION_NAME_MAP.put("parent:plan:edit", "编辑计划");

        // 教师功能权限
        PERMISSION_NAME_MAP.put("teaching:class:view", "查看班级");
        PERMISSION_NAME_MAP.put("teaching:content:edit", "编辑内容");
        PERMISSION_NAME_MAP.put("teaching:report:view", "查看报告");
    }

    /**
     * 管理员测试接口
     */
    @GetMapping("/test")
    public R test() {
        System.out.println("管理员测试接口被调用");
        return R.ok("管理员接口测试成功").data(new HashMap<String, Object>() {{
            put("timestamp", new Date());
            put("status", "服务正常");
        }});
    }

    /**
     * 管理员POST测试接口
     */
    @PostMapping("/test-post")
    public R testPost(@RequestBody Map<String, Object> request) {
        System.out.println("管理员POST测试接口被调用，数据: " + request);
        return R.ok("POST测试成功").data(request);
    }

    /**
     * 获取管理数据 - 用户、角色、权限信息
     */
    @GetMapping("/users")
    public R getUserManagement() {
        try {
            logger.debug("获取管理数据接口被调用");
            Map<String, Object> data = new HashMap<>();

            // 从数据库查询所有用户
            List<SysUser> allUsers = sysUserMapper.findAll();
            List<Map<String, Object>> users = new ArrayList<>();
            for (SysUser user : allUsers) {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("id", user.getId());
                userMap.put("username", user.getUsername());
                userMap.put("nickname", user.getNickname());
                userMap.put("role", user.getRole());
                // 邮箱和手机号需要先解密再脱敏
                String email = null;
                String phone = null;
                if (user.getEmail() != null && !user.getEmail().isEmpty()) {
                    try {
                        email = DataEncryptionUtils.decryptSensitiveField(user.getEmail());
                    } catch (Exception e) {
                        email = user.getEmail();
                    }
                }
                if (user.getPhone() != null && !user.getPhone().isEmpty()) {
                    try {
                        phone = DataEncryptionUtils.decryptSensitiveField(user.getPhone());
                    } catch (Exception e) {
                        phone = user.getPhone();
                    }
                }
                userMap.put("email", email != null ? maskEmail(email) : null);
                userMap.put("phone", phone != null ? maskPhone(phone) : null);
                userMap.put("status", "0"); // 默认正常状态
                userMap.put("createTime", user.getCreatedTime() != null ? user.getCreatedTime().toString() : "");
                users.add(userMap);
            }

            // 角色列表 - 与你的数据库角色数据保持一致
            List<Map<String, Object>> roles = Arrays.asList(
                    createRole(1L, "超级管理员", "admin", "拥有所有权限"),
                    createRole(2L, "家长", "parent", "查看孩子学习进度"),
                    createRole(3L, "幼儿", "child", "学习功能权限"),
                    createRole(4L, "教师", "teacher", "教学管理权限")
            );

            // 权限列表 - 从权限映射表生成
            List<Map<String, Object>> permissions = new ArrayList<>();
            for (Map.Entry<String, String> entry : PERMISSION_NAME_MAP.entrySet()) {
                String category = getPermissionCategory(entry.getKey());
                permissions.add(createPermission(entry.getKey(), entry.getValue(), category));
            }

            // 获取每个角色的现有权限
            Map<Long, List<String>> rolePermissions = new HashMap<>();
            for (Map<String, Object> role : roles) {
                Long roleId = (Long) role.get("id");
                try {
                    List<SysRolePermission> existingPermissions = sysRolePermissionMapper.findByRoleId(roleId);
                    List<String> permissionCodes = existingPermissions.stream()
                            .map(SysRolePermission::getPermissionCode)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    rolePermissions.put(roleId, permissionCodes);
                    logger.debug("角色 {} 的权限: {}", roleId, permissionCodes);
                } catch (Exception e) {
                    logger.error("获取角色 {} 权限失败: {}", roleId, e.getMessage(), e);
                    rolePermissions.put(roleId, new ArrayList<>());
                }
            }

            data.put("users", users);
            data.put("roles", roles);
            data.put("permissions", permissions);
            data.put("rolePermissions", rolePermissions);

            logger.debug("返回管理数据成功");
            return R.ok("获取管理数据成功").data(data);
        } catch (Exception e) {
            logger.error("获取管理数据异常: {}", e.getMessage(), e);
            return R.error("获取管理数据失败: " + e.getMessage());
        }
    }

    /**
     * 更新角色权限 - 核心修复方法
     */
    @PostMapping("/role/permissions")
    public R updateRolePermissions(@RequestBody Map<String, Object> request) {
        System.out.println("=== 开始更新角色权限 ===");
        System.out.println("完整请求数据: " + request);

        try {
            // 参数验证
            if (request.get("roleId") == null) {
                System.err.println("错误: 角色ID为空");
                return R.error("角色ID不能为空");
            }

            Long roleId;
            try {
                roleId = Long.valueOf(request.get("roleId").toString());
                System.out.println("角色ID: " + roleId);
            } catch (NumberFormatException e) {
                System.err.println("错误: 角色ID格式错误 - " + request.get("roleId"));
                return R.error("角色ID格式错误");
            }

            // 安全地获取权限列表
            List<String> permissions = new ArrayList<>();
            Object permissionsObj = request.get("permissions");
            System.out.println("权限原始数据: " + permissionsObj);
            System.out.println("权限数据类型: " + (permissionsObj != null ? permissionsObj.getClass().getName() : "null"));

            if (permissionsObj instanceof List) {
                @SuppressWarnings("unchecked")
                List<Object> tempList = (List<Object>) permissionsObj;
                for (Object item : tempList) {
                    if (item != null) {
                        String permissionCode = item.toString().trim();
                        if (!permissionCode.isEmpty() && PERMISSION_NAME_MAP.containsKey(permissionCode)) {
                            permissions.add(permissionCode);
                        } else {
                            System.err.println("跳过无效权限: " + permissionCode);
                        }
                    }
                }
            } else if (permissionsObj instanceof String) {
                // 处理字符串格式的权限
                String[] permArray = ((String) permissionsObj).split(",");
                for (String perm : permArray) {
                    String permissionCode = perm.trim();
                    if (!permissionCode.isEmpty() && PERMISSION_NAME_MAP.containsKey(permissionCode)) {
                        permissions.add(permissionCode);
                    } else {
                        System.err.println("跳过无效权限: " + permissionCode);
                    }
                }
            }

            System.out.println("解析后的有效权限列表: " + permissions);
            System.out.println("有效权限数量: " + permissions.size());

            // 开始事务操作
            try {
                // 先删除该角色的所有权限
                int deleteCount = sysRolePermissionMapper.deleteByRoleId(roleId);
                System.out.println("删除原有权限数量: " + deleteCount);

                // 插入新的权限
                int insertCount = 0;
                if (permissions != null && !permissions.isEmpty()) {
                    for (String permissionCode : permissions) {
                        if (permissionCode != null && !permissionCode.trim().isEmpty()) {
                            SysRolePermission permission = new SysRolePermission();
                            permission.setRoleId(roleId);
                            permission.setPermissionCode(permissionCode.trim());
                            permission.setPermissionName(PERMISSION_NAME_MAP.get(permissionCode.trim()));
                            permission.setCreateTime(new Date());

                            try {
                                int result = sysRolePermissionMapper.insert(permission);
                                if (result > 0) {
                                    insertCount++;
                                    System.out.println("插入权限成功: " + permissionCode);
                                } else {
                                    System.err.println("插入权限失败: " + permissionCode);
                                }
                            } catch (Exception e) {
                                System.err.println("插入权限异常 (" + permissionCode + "): " + e.getMessage());
                                // 继续插入其他权限，不中断
                            }
                        }
                    }
                }

                System.out.println("成功插入新权限数量: " + insertCount);

                Map<String, Object> result = new HashMap<>();
                result.put("roleId", roleId);
                result.put("permissions", permissions);
                result.put("updateTime", new Date());
                result.put("deleteCount", deleteCount);
                result.put("insertCount", insertCount);

                System.out.println("=== 权限更新成功 ===");
                return R.ok("权限更新成功").data(result);

            } catch (Exception e) {
                System.err.println("数据库操作失败: " + e.getMessage());
                e.printStackTrace();
                return R.error("数据库操作失败: " + e.getMessage());
            }

        } catch (Exception e) {
            System.err.println("权限更新失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("权限更新失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户角色
     */
    @PostMapping("/user/role")
    public R updateUserRole(@RequestBody Map<String, Object> request) {
        try {
            System.out.println("更新用户角色请求: " + request);

            if (request.get("userId") == null || request.get("roleId") == null) {
                return R.error("用户ID和角色ID不能为空");
            }

            Long userId = Long.valueOf(request.get("userId").toString());
            Long roleId = Long.valueOf(request.get("roleId").toString());

            // 这里应该调用服务更新数据库中的用户角色关系
            // 暂时返回成功
            Map<String, Object> result = new HashMap<>();
            result.put("userId", userId);
            result.put("roleId", roleId);
            result.put("updateTime", new Date());

            System.out.println("用户角色更新成功: 用户 " + userId + " -> 角色 " + roleId);

            return R.ok("用户角色更新成功").data(result);
        } catch (Exception e) {
            System.err.println("用户角色更新失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("用户角色更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取角色权限
     */
    @GetMapping("/role/{roleId}/permissions")
    public R getRolePermissions(@PathVariable Long roleId) {
        try {
            System.out.println("获取角色权限: " + roleId);

            List<SysRolePermission> permissions = sysRolePermissionMapper.findByRoleId(roleId);
            List<String> permissionCodes = permissions.stream()
                    .map(SysRolePermission::getPermissionCode)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            Map<String, Object> result = new HashMap<>();
            result.put("roleId", roleId);
            result.put("permissions", permissionCodes);

            logger.debug("角色 {} 的权限: {}", roleId, permissionCodes);

            return R.ok("获取角色权限成功").data(result);
        } catch (Exception e) {
            System.err.println("获取角色权限失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("获取角色权限失败: " + e.getMessage());
        }
    }

    /**
     * 根据权限代码获取权限分类
     */
    private String getPermissionCategory(String permissionCode) {
        if (permissionCode.startsWith("system:")) {
            return "系统管理";
        }
        if (permissionCode.startsWith("learning:")) {
            return "学习功能";
        }
        if (permissionCode.startsWith("parent:")) {
            return "家长功能";
        }
        if (permissionCode.startsWith("teaching:")) {
            return "教师功能";
        }
        return "其他权限";
    }

    /**
     * 创建用户数据
     */
    private Map<String, Object> createUser(Long id, String username, String nickname, String role, String status, String createTime) {
        Map<String, Object> user = new HashMap<>();
        user.put("id", id);
        user.put("username", username);
        user.put("nickname", nickname);
        user.put("role", role);
        user.put("status", status);
        user.put("createTime", createTime);
        return user;
    }

    /**
     * 创建角色数据
     */
    private Map<String, Object> createRole(Long id, String name, String key, String description) {
        Map<String, Object> role = new HashMap<>();
        role.put("id", id);
        role.put("name", name);
        role.put("key", key);
        role.put("description", description);
        return role;
    }

    /**
     * 创建权限数据
     */
    private Map<String, Object> createPermission(String code, String name, String category) {
        Map<String, Object> permission = new HashMap<>();
        permission.put("code", code);
        permission.put("name", name);
        permission.put("category", category);
        return permission;
    }

    /**
     * 获取所有有效权限代码列表
     */
    @GetMapping("/permissions/list")
    public R getAllPermissions() {
        try {
            List<Map<String, Object>> permissions = new ArrayList<>();
            for (Map.Entry<String, String> entry : PERMISSION_NAME_MAP.entrySet()) {
                String category = getPermissionCategory(entry.getKey());
                permissions.add(createPermission(entry.getKey(), entry.getValue(), category));
            }

            Map<String, Object> result = new HashMap<>();
            result.put("permissions", permissions);
            result.put("total", permissions.size());

            return R.ok("获取权限列表成功").data(result);
        } catch (Exception e) {
            System.err.println("获取权限列表失败: " + e.getMessage());
            return R.error("获取权限列表失败: " + e.getMessage());
        }
    }

    /**
     * 验证权限代码是否有效
     */
    @PostMapping("/permissions/validate")
    public R validatePermissions(@RequestBody List<String> permissionCodes) {
        try {
            List<String> validPermissions = new ArrayList<>();
            List<String> invalidPermissions = new ArrayList<>();

            for (String code : permissionCodes) {
                if (PERMISSION_NAME_MAP.containsKey(code)) {
                    validPermissions.add(code);
                } else {
                    invalidPermissions.add(code);
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("validPermissions", validPermissions);
            result.put("invalidPermissions", invalidPermissions);
            result.put("validCount", validPermissions.size());
            result.put("invalidCount", invalidPermissions.size());

            return R.ok("权限验证完成").data(result);
        } catch (Exception e) {
            System.err.println("权限验证失败: " + e.getMessage());
            return R.error("权限验证失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有用户（按角色分类）
     */
    @GetMapping("/users/all")
    public R getAllUsers() {
        try {
            List<SysUser> allUsers = sysUserMapper.findAll();
            
            // 按角色分类
            Map<String, List<Map<String, Object>>> usersByRole = new HashMap<>();
            usersByRole.put("admin", new ArrayList<>());
            usersByRole.put("teacher", new ArrayList<>());
            usersByRole.put("child", new ArrayList<>());
            usersByRole.put("parent", new ArrayList<>());
            
            for (SysUser user : allUsers) {
                Map<String, Object> userMap = convertUserToMap(user);
                String role = user.getRole() != null ? user.getRole() : "parent";
                if (!usersByRole.containsKey(role)) {
                    usersByRole.put(role, new ArrayList<>());
                }
                usersByRole.get(role).add(userMap);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("usersByRole", usersByRole);
            result.put("total", allUsers.size());
            
            return R.ok("获取用户列表成功").data(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 编辑用户
     */
    @PostMapping("/user/update")
    @Transactional
    public R updateUser(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            if (request.get("id") == null) {
                return R.error("用户ID不能为空");
            }

            Long userId = Long.valueOf(request.get("id").toString());
            SysUser existingUser = sysUserMapper.findById(userId);
            if (existingUser == null) {
                return R.error("用户不存在");
            }

            // 更新用户信息
            if (request.get("username") != null) {
                existingUser.setUsername(request.get("username").toString().trim());
            }
            if (request.get("nickname") != null) {
                existingUser.setNickname(request.get("nickname").toString().trim());
            }
            if (request.get("email") != null) {
                existingUser.setEmail(UserDataHelper.processAndEncryptEmail(request.get("email").toString()));
            }
            if (request.get("phone") != null) {
                existingUser.setPhone(UserDataHelper.processAndEncryptPhone(request.get("phone").toString()));
            }

            // 更新密码（如果提供）
            if (request.get("password") != null && !request.get("password").toString().trim().isEmpty()) {
                String password = UserDataHelper.decryptPassword(request.get("password").toString().trim());
                // 使用BCrypt加密
                String encodedPassword = PasswordEncoderUtil.encode(password);
                sysUserMapper.updatePassword(userId, encodedPassword);
            }

            // 更新用户基本信息
            sysUserMapper.updateUser(existingUser);

            // 更新角色（如果提供）
            if (request.get("role") != null) {
                String roleKey = request.get("role").toString();
                Long roleId = sysRoleMapper.findRoleIdByRoleKey(roleKey);
                if (roleId != null) {
                    // 先删除旧的角色关联
                    sysRoleMapper.deleteUserRoleByUserId(userId);
                    // 插入新的角色关联
                    sysRoleMapper.insertUserRole(userId, roleId);
                    existingUser.setRole(roleKey);
                }
            }

            // 记录安全日志
            String ipAddress = SecurityAuditLogger.getClientIp(httpRequest);
            SecurityAuditLogger.logPasswordChange(existingUser.getUsername(), true, ipAddress, 
                SecurityAuditLogger.getUserAgent(httpRequest));

            return R.ok("用户更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("更新用户失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @PostMapping("/user/delete")
    @Transactional
    public R deleteUser(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            if (request.get("userId") == null) {
                return R.error("用户ID不能为空");
            }

            Long userId = Long.valueOf(request.get("userId").toString());
            SysUser user = sysUserMapper.findById(userId);
            if (user == null) {
                return R.error("用户不存在");
            }

            // 先删除用户角色关联
            sysRoleMapper.deleteUserRoleByUserId(userId);
            // 再删除用户
            int result = sysUserMapper.deleteById(userId);

            if (result > 0) {
                // 记录安全日志
                String ipAddress = SecurityAuditLogger.getClientIp(httpRequest);
                SecurityAuditLogger.logDataDelete(user.getUsername(), "USER", userId, ipAddress,
                    SecurityAuditLogger.getUserAgent(httpRequest));

                return R.ok("用户删除成功");
            } else {
                return R.error("用户删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("删除用户失败: " + e.getMessage());
        }
    }

    /**
     * 管理员添加用户（带角色选择）
     */
    @PostMapping("/user/add")
    @Transactional
    public R addUser(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            // 验证必填字段
            if (request.get("username") == null || request.get("username").toString().trim().isEmpty()) {
                return R.error("用户名不能为空");
            }
            if (request.get("password") == null || request.get("password").toString().trim().isEmpty()) {
                return R.error("密码不能为空");
            }
            if (request.get("role") == null || request.get("role").toString().trim().isEmpty()) {
                return R.error("角色不能为空");
            }

            String username = request.get("username").toString().trim();
            String password = request.get("password").toString().trim();
            String role = request.get("role").toString().trim();

            // 检查用户名是否已存在
            if (sysUserMapper.countByUsername(username) > 0) {
                return R.error("用户名已存在");
            }

            // 解密前端加密的密码
            password = UserDataHelper.decryptPassword(password);

            // 验证密码强度
            if (!ValidationPatterns.PASSWORD_PATTERN.matcher(password).matches()) {
                return R.error("密码必须为8-20位，且包含字母和数字");
            }

            // 创建用户
            SysUser user = new SysUser();
            user.setUsername(username);
            user.setPassword(PasswordEncoderUtil.encode(password));
            user.setRole(role);
            user.setNickname(request.get("nickname") != null ? request.get("nickname").toString().trim() : null);
            
            // 处理邮箱和手机号（加密存储）
            user.setEmail(UserDataHelper.processAndEncryptEmail(
                request.get("email") != null ? request.get("email").toString() : null));
            user.setPhone(UserDataHelper.processAndEncryptPhone(
                request.get("phone") != null ? request.get("phone").toString() : null));
            
            user.setUserType(UserDataHelper.getUserTypeByRole(role));
            user.setCreatedTime(LocalDateTime.now());

            // 插入用户
            int result = sysUserMapper.insert(user);
            if (result > 0) {
                // 插入用户角色关联
                Long roleId = sysRoleMapper.findRoleIdByRoleKey(role);
                if (roleId != null) {
                    sysRoleMapper.insertUserRole(user.getId(), roleId);
                }

                // 记录安全日志
                String ipAddress = SecurityAuditLogger.getClientIp(httpRequest);
                SecurityAuditLogger.logRegister(user.getUsername(), role, true, ipAddress,
                    SecurityAuditLogger.getUserAgent(httpRequest));

                return R.ok("用户添加成功");
            } else {
                return R.error("用户添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("添加用户失败: " + e.getMessage());
        }
    }

    /**
     * 将SysUser转换为Map（脱敏处理）
     */
    private Map<String, Object> convertUserToMap(SysUser user) {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", user.getId());
        userMap.put("username", user.getUsername());
        userMap.put("nickname", user.getNickname());
        userMap.put("role", user.getRole());
        
        // 邮箱和手机号脱敏显示
        if (user.getEmail() != null && !user.getEmail().isEmpty()) {
            try {
                // 尝试解密（如果是加密的）
                String email = DataEncryptionUtils.decryptSensitiveField(user.getEmail());
                userMap.put("email", maskEmail(email));
            } catch (Exception e) {
                // 如果解密失败，可能是未加密的，直接脱敏
                userMap.put("email", maskEmail(user.getEmail()));
            }
        } else {
            userMap.put("email", null);
        }
        
        if (user.getPhone() != null && !user.getPhone().isEmpty()) {
            try {
                // 尝试解密（如果是加密的）
                String phone = DataEncryptionUtils.decryptSensitiveField(user.getPhone());
                userMap.put("phone", maskPhone(phone));
            } catch (Exception e) {
                // 如果解密失败，可能是未加密的，直接脱敏
                userMap.put("phone", maskPhone(user.getPhone()));
            }
        } else {
            userMap.put("phone", null);
        }
        
        userMap.put("status", "0");
        userMap.put("createTime", user.getCreatedTime() != null ? user.getCreatedTime().toString() : "");
        return userMap;
    }

    /**
     * 脱敏邮箱
     */
    private String maskEmail(String email) {
        if (email == null || email.isEmpty()) {
            return "";
        }
        int atIndex = email.indexOf("@");
        if (atIndex > 1) {
            return email.charAt(0) + "**" + email.substring(atIndex);
        }
        return "***" + (atIndex > 0 ? email.substring(atIndex) : "");
    }

    /**
     * 脱敏手机号
     */
    private String maskPhone(String phone) {
        if (phone == null || phone.isEmpty()) {
            return "";
        }
        if (phone.length() == 11) {
            return phone.substring(0, 3) + "****" + phone.substring(7);
        }
        return "****";
    }

    /**
     * 获取待审核内容列表（只显示待审核状态的文件）
     */
    @GetMapping("/review/pending")
    public R getPendingReviewItems(@RequestParam(required = false) String type) {
        try {
            List<Map<String, Object>> items = new ArrayList<>();
            
            System.out.println("=== 获取待审核内容 ===");
            System.out.println("请求类型: " + type);
            
            // 先尝试同步文件系统中的文件到数据库
            syncFilesToDatabase(type);
            
            // 修复现有记录的file_type和review_status
            fixExistingFileRecords();
            
            // 从数据库查询待审核的文件（reviewStatus=0或null）
            List<com.childenglish.entity.FileInfo> pendingFiles = fileInfoMapper.selectByReviewStatus(0, type);
            
            System.out.println("查询到待审核文件数量: " + (pendingFiles != null ? pendingFiles.size() : 0));
            
            for (com.childenglish.entity.FileInfo fileInfo : pendingFiles) {
                System.out.println("文件信息: fileName=" + fileInfo.getFileName() + 
                    ", fileType=" + fileInfo.getFileType() + 
                    ", reviewStatus=" + fileInfo.getReviewStatus());
                Map<String, Object> file = new HashMap<>();
                file.put("id", fileInfo.getId());
                file.put("fileName", fileInfo.getFileName());
                file.put("originalName", fileInfo.getOriginalName());
                file.put("displayName", fileInfo.getOriginalName() != null ? 
                    fileInfo.getOriginalName() : fileInfo.getFileName());
                file.put("size", fileInfo.getFileSize());
                file.put("uploadTime", fileInfo.getUploadTime() != null ? fileInfo.getUploadTime().getTime() : System.currentTimeMillis());
                file.put("type", fileInfo.getFileType());
                file.put("uploadUser", fileInfo.getUploadUser() != null ? fileInfo.getUploadUser() : "未知");
                file.put("reviewStatus", fileInfo.getReviewStatus() != null ? fileInfo.getReviewStatus() : 0);
                items.add(file);
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("items", items);
            return R.ok("获取待审核内容成功").data(data);
        } catch (Exception e) {
            System.err.println("获取待审核内容失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("获取待审核内容失败: " + e.getMessage());
        }
    }

    /**
     * 修复现有记录的file_type和review_status
     */
    private void fixExistingFileRecords() {
        try {
            // 查询所有文件
            List<com.childenglish.entity.FileInfo> allFiles = fileInfoMapper.selectAll(null);
            
            for (com.childenglish.entity.FileInfo fileInfo : allFiles) {
                boolean needUpdate = false;
                String newFileType = fileInfo.getFileType();
                Integer newReviewStatus = fileInfo.getReviewStatus();
                
                // 如果file_type是"document"、"other"或为空，尝试修复
                if (fileInfo.getFileType() == null || fileInfo.getFileType().isEmpty() || 
                    "document".equals(fileInfo.getFileType()) || "other".equals(fileInfo.getFileType())) {
                    String originalName = fileInfo.getOriginalName();
                    String fileName = fileInfo.getFileName();
                    String nameToCheck = originalName != null ? originalName : fileName;
                    String mimeType = fileInfo.getMimeType();
                    
                    if (nameToCheck != null && nameToCheck.contains(".")) {
                        String extension = nameToCheck.substring(nameToCheck.lastIndexOf('.') + 1).toLowerCase();
                        // 课件类型
                        if (Arrays.asList("pdf", "ppt", "pptx", "doc", "docx", "txt").contains(extension)) {
                            newFileType = "courseware";
                            needUpdate = true;
                        } 
                        // 绘本类型（图片）
                        else if (Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp").contains(extension)) {
                            newFileType = "picturebook";
                            needUpdate = true;
                        }
                        // 音频类型
                        else if (Arrays.asList("mp3", "wav", "ogg", "flac", "aac", "m4a", "wma", "mp4").contains(extension)) {
                            newFileType = "audio";
                            needUpdate = true;
                        }
                        // 如果无法通过扩展名判断，尝试通过 MIME 类型判断
                        else if (mimeType != null && !mimeType.isEmpty()) {
                            if (mimeType.startsWith("audio/")) {
                                newFileType = "audio";
                                needUpdate = true;
                            } else if (mimeType.startsWith("image/")) {
                                newFileType = "picturebook";
                                needUpdate = true;
                            } else if (mimeType.contains("pdf") || mimeType.contains("document") || 
                                      mimeType.contains("presentation") || mimeType.contains("text")) {
                                newFileType = "courseware";
                                needUpdate = true;
                            }
                        }
                    } else if (mimeType != null && !mimeType.isEmpty()) {
                        // 如果没有扩展名，通过 MIME 类型判断
                        if (mimeType.startsWith("audio/")) {
                            newFileType = "audio";
                            needUpdate = true;
                        } else if (mimeType.startsWith("image/")) {
                            newFileType = "picturebook";
                            needUpdate = true;
                        } else if (mimeType.contains("pdf") || mimeType.contains("document") || 
                                  mimeType.contains("presentation") || mimeType.contains("text")) {
                            newFileType = "courseware";
                            needUpdate = true;
                        }
                    }
                }
                
                // 如果review_status为NULL，设置为0（待审核）
                if (fileInfo.getReviewStatus() == null) {
                    newReviewStatus = 0;
                    needUpdate = true;
                }
                
                // 如果需要更新，执行更新
                if (needUpdate) {
                    fileInfoMapper.updateFileTypeAndReviewStatus(fileInfo.getFileName(), newFileType, newReviewStatus);
                    System.out.println("修复文件记录: fileName=" + fileInfo.getFileName() + 
                        ", fileType=" + newFileType + ", reviewStatus=" + newReviewStatus);
                }
            }
        } catch (Exception e) {
            System.err.println("修复现有文件记录失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 同步文件系统中的文件到数据库
     */
    private void syncFilesToDatabase(String type) {
        try {
            // 从文件系统获取文件列表
            List<Map<String, Object>> fileSystemFiles = fileStorageService.getFileListFromFileSystem(type);
            
            for (Map<String, Object> fileMap : fileSystemFiles) {
                String fileName = (String) fileMap.get("fileName");
                
                // 检查数据库中是否已存在该文件
                com.childenglish.entity.FileInfo existingFile = fileInfoMapper.selectByFileName(fileName);
                
                if (existingFile == null) {
                    // 文件不存在于数据库，创建新记录
                    com.childenglish.entity.FileInfo fileInfo = new com.childenglish.entity.FileInfo();
                    fileInfo.setFileName(fileName);
                    fileInfo.setOriginalName((String) fileMap.get("originalName"));
                    fileInfo.setFileSize((Long) fileMap.get("size"));
                    fileInfo.setFileType((String) fileMap.get("type"));
                    fileInfo.setMimeType((String) fileMap.get("mimeType"));
                    fileInfo.setStatus(2); // 合并完成
                    fileInfo.setReviewStatus(0); // 待审核
                    fileInfo.setChunked(0);
                    
                    // 设置上传时间
                    Long uploadTime = (Long) fileMap.get("uploadTime");
                    if (uploadTime != null) {
                        fileInfo.setUploadTime(new Date(uploadTime));
                        fileInfo.setCompleteTime(new Date(uploadTime));
                    } else {
                        fileInfo.setUploadTime(new Date());
                        fileInfo.setCompleteTime(new Date());
                    }
                    
                    // 尝试从文件名推断文件类型
                    if (fileInfo.getFileType() == null || fileInfo.getFileType().isEmpty() || "document".equals(fileInfo.getFileType())) {
                        String originalName = fileInfo.getOriginalName();
                        String nameToCheck = originalName != null ? originalName : fileName;
                        
                        if (nameToCheck != null && nameToCheck.contains(".")) {
                            String extension = nameToCheck.substring(nameToCheck.lastIndexOf('.') + 1).toLowerCase();
                            if (Arrays.asList("pdf", "ppt", "pptx", "doc", "docx", "txt").contains(extension)) {
                                fileInfo.setFileType("courseware");
                            } else if (Arrays.asList("jpg", "jpeg", "png", "gif").contains(extension)) {
                                fileInfo.setFileType("picturebook");
                            } else if ("document".equals(fileInfo.getFileType())) {
                                // 如果fileType是"document"，默认改为"courseware"
                                fileInfo.setFileType("courseware");
                            }
                        } else if ("document".equals(fileInfo.getFileType())) {
                            // 如果fileType是"document"但无法判断扩展名，默认改为"courseware"
                            fileInfo.setFileType("courseware");
                        }
                    }
                    
                    fileInfoMapper.insert(fileInfo);
                    System.out.println("同步文件到数据库: " + fileName);
                }
            }
        } catch (Exception e) {
            System.err.println("同步文件到数据库失败: " + e.getMessage());
            // 同步失败不影响查询结果
        }
    }

    /**
     * 审核通过
     */
    @PostMapping("/review/approve")
    public R approveContent(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            String fileName = (String) request.get("fileName");
            String type = (String) request.get("type");
            
            if (fileName == null || fileName.isEmpty()) {
                return R.error("文件名不能为空");
            }
            
            // 获取当前登录的管理员用户名
            String reviewer = getCurrentUsername(httpRequest);
            
            // 更新文件的审核状态为已通过(1)
            Date reviewTime = new Date();
            System.out.println("=== 审核通过操作 ===");
            System.out.println("fileName: " + fileName);
            System.out.println("reviewStatus: 1 (已通过)");
            System.out.println("reviewer: " + reviewer);
            
            int updateCount = fileInfoMapper.updateReviewStatus(fileName, 1, null, reviewer, reviewTime);
            
            System.out.println("更新记录数: " + updateCount);
            
            if (updateCount == 0) {
                return R.error("文件不存在或更新失败");
            }
            
            // 验证更新是否成功
            com.childenglish.entity.FileInfo updatedFile = fileInfoMapper.selectByFileName(fileName);
            if (updatedFile != null) {
                System.out.println("更新后验证: fileName=" + updatedFile.getFileName() + 
                    ", reviewStatus=" + updatedFile.getReviewStatus() + 
                    ", reviewer=" + updatedFile.getReviewer());
            }
            
            // 获取文件信息，查找上传用户
            com.childenglish.entity.FileInfo fileInfo = fileInfoMapper.selectByFileName(fileName);
            if (fileInfo != null && fileInfo.getUploadUser() != null) {
                // 查找上传用户的ID
                try {
                    SysUser uploadUser = sysUserMapper.findByUsername(fileInfo.getUploadUser());
                    if (uploadUser != null) {
                        // 发送审核通过通知
                        notificationService.sendReviewApprovedNotification(
                            uploadUser.getId(), 
                            fileInfo.getOriginalName() != null ? fileInfo.getOriginalName() : fileName,
                            fileInfo.getFileType() != null ? fileInfo.getFileType() : type
                        );
                    }
                } catch (Exception e) {
                    System.err.println("发送通知失败: " + e.getMessage());
                    // 通知发送失败不影响审核结果
                }
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("fileName", fileName);
            data.put("type", type);
            data.put("status", "approved");
            data.put("reviewer", reviewer);
            data.put("reviewTime", reviewTime);
            
            return R.ok("审核通过成功").data(data);
        } catch (Exception e) {
            System.err.println("审核失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("审核失败: " + e.getMessage());
        }
    }

    /**
     * 审核拒绝
     */
    @PostMapping("/review/reject")
    public R rejectContent(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        try {
            String fileName = (String) request.get("fileName");
            String type = (String) request.get("type");
            String reason = (String) request.get("reason");
            
            if (fileName == null || fileName.isEmpty()) {
                return R.error("文件名不能为空");
            }
            
            // 获取当前登录的管理员用户名
            String reviewer = getCurrentUsername(httpRequest);
            
            // 更新文件的审核状态为已拒绝(2)
            Date reviewTime = new Date();
            int updateCount = fileInfoMapper.updateReviewStatus(fileName, 2, reason, reviewer, reviewTime);
            
            if (updateCount == 0) {
                return R.error("文件不存在或更新失败");
            }
            
            // 获取文件信息，查找上传用户
            com.childenglish.entity.FileInfo fileInfo = fileInfoMapper.selectByFileName(fileName);
            if (fileInfo != null && fileInfo.getUploadUser() != null) {
                // 查找上传用户的ID
                try {
                    SysUser uploadUser = sysUserMapper.findByUsername(fileInfo.getUploadUser());
                    if (uploadUser != null) {
                        // 发送审核拒绝通知
                        notificationService.sendReviewRejectedNotification(
                            uploadUser.getId(), 
                            fileInfo.getOriginalName() != null ? fileInfo.getOriginalName() : fileName,
                            fileInfo.getFileType() != null ? fileInfo.getFileType() : type,
                            reason
                        );
                    }
                } catch (Exception e) {
                    System.err.println("发送通知失败: " + e.getMessage());
                    // 通知发送失败不影响审核结果
                }
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("fileName", fileName);
            data.put("type", type);
            data.put("status", "rejected");
            data.put("reason", reason);
            data.put("reviewer", reviewer);
            data.put("reviewTime", reviewTime);
            
            return R.ok("已拒绝该内容").data(data);
        } catch (Exception e) {
            System.err.println("操作失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户名
     */
    private String getCurrentUsername(HttpServletRequest request) {
        try {
            // 从请求头或session中获取用户名
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                // 这里应该解析JWT token获取用户名
                // 暂时返回"管理员"
            }
            return "管理员";
        } catch (Exception e) {
            return "管理员";
        }
    }

    /**
     * 获取已审核内容（已通过和已拒绝的文件）
     */
    @GetMapping("/review/reviewed")
    public R getReviewedContent() {
        try {
            List<Map<String, Object>> items = new ArrayList<>();
            
            // 查询已通过的文件（reviewStatus=1）
            List<com.childenglish.entity.FileInfo> approvedFiles = fileInfoMapper.selectByReviewStatus(1, null);
            
            // 查询已拒绝的文件（reviewStatus=2）
            List<com.childenglish.entity.FileInfo> rejectedFiles = fileInfoMapper.selectByReviewStatus(2, null);
            
            // 处理已通过的文件
            for (com.childenglish.entity.FileInfo fileInfo : approvedFiles) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", fileInfo.getId());
                item.put("fileName", fileInfo.getFileName());
                item.put("originalName", fileInfo.getOriginalName());
                item.put("displayName", fileInfo.getOriginalName() != null ? fileInfo.getOriginalName() : fileInfo.getFileName());
                item.put("fileType", fileInfo.getFileType());
                item.put("size", fileInfo.getFileSize());
                item.put("uploadTime", fileInfo.getUploadTime());
                item.put("uploadUser", fileInfo.getUploadUser());
                item.put("reviewStatus", fileInfo.getReviewStatus());
                item.put("reviewer", fileInfo.getReviewer());
                item.put("reviewTime", fileInfo.getReviewTime());
                item.put("reviewReason", fileInfo.getReviewReason());
                items.add(item);
            }
            
            // 处理已拒绝的文件
            for (com.childenglish.entity.FileInfo fileInfo : rejectedFiles) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", fileInfo.getId());
                item.put("fileName", fileInfo.getFileName());
                item.put("originalName", fileInfo.getOriginalName());
                item.put("displayName", fileInfo.getOriginalName() != null ? fileInfo.getOriginalName() : fileInfo.getFileName());
                item.put("fileType", fileInfo.getFileType());
                item.put("size", fileInfo.getFileSize());
                item.put("uploadTime", fileInfo.getUploadTime());
                item.put("uploadUser", fileInfo.getUploadUser());
                item.put("reviewStatus", fileInfo.getReviewStatus());
                item.put("reviewer", fileInfo.getReviewer());
                item.put("reviewTime", fileInfo.getReviewTime());
                item.put("reviewReason", fileInfo.getReviewReason());
                items.add(item);
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("items", items);
            data.put("approvedCount", approvedFiles.size());
            data.put("rejectedCount", rejectedFiles.size());
            data.put("totalCount", items.size());
            
            return R.ok("获取已审核内容成功").data(data);
        } catch (Exception e) {
            System.err.println("获取已审核内容失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("获取已审核内容失败: " + e.getMessage());
        }
    }

    /**
     * 获取数据监控信息
     */
    @GetMapping("/monitor/data")
    public R getMonitorData() {
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 用户统计
            List<SysUser> allUsers = sysUserMapper.findAll();
            data.put("totalUsers", allUsers.size());
            
            // 在线用户数
            data.put("onlineUsers", onlineUserService.getOnlineUserCount());
            
            // 文件统计
            List<Map<String, Object>> coursewares = fileStorageService.getFileList("courseware");
            List<Map<String, Object>> picturebooks = fileStorageService.getFileList("picturebook");
            List<Map<String, Object>> audios = fileStorageService.getFileList("audio");
            
            data.put("totalCoursewares", coursewares.size());
            data.put("totalPicturebooks", picturebooks.size());
            data.put("totalAudios", audios.size());
            
            // 审核统计 - 直接从数据库查询，确保与审核界面一致
            int approvedCount = 0;
            int pendingCount = 0;
            int rejectedCount = 0;
            
            try {
                // 查询所有文件（不限制审核状态）
                List<com.childenglish.entity.FileInfo> allFiles = fileInfoMapper.selectAll(null);
                
                logger.debug("=== 统计审核数据 ===");
                logger.debug("查询到文件总数: {}", allFiles != null ? allFiles.size() : 0);
                
                for (com.childenglish.entity.FileInfo fileInfo : allFiles) {
                    Integer reviewStatus = fileInfo.getReviewStatus();
                    logger.debug("文件: {}, fileType: {}, reviewStatus: {}", 
                        fileInfo.getFileName(), fileInfo.getFileType(), reviewStatus);
                    
                    if (reviewStatus == null || reviewStatus == 0) {
                        pendingCount++;
                    } else if (reviewStatus == 1) {
                        approvedCount++;
                    } else if (reviewStatus == 2) {
                        rejectedCount++;
                    }
                }
                
                logger.debug("统计结果: 待审核={}, 已通过={}, 已拒绝={}", 
                    pendingCount, approvedCount, rejectedCount);
            } catch (Exception e) {
                System.err.println("统计审核数据失败: " + e.getMessage());
                // 如果数据库查询失败，回退到文件列表统计
                List<Map<String, Object>> allFiles = new ArrayList<>();
                allFiles.addAll(coursewares);
                allFiles.addAll(picturebooks);
                allFiles.addAll(audios);
                
                for (Map<String, Object> file : allFiles) {
                    Integer reviewStatus = (Integer) file.get("reviewStatus");
                    if (reviewStatus == null || reviewStatus == 0) {
                        pendingCount++;
                    } else if (reviewStatus == 1) {
                        approvedCount++;
                    } else if (reviewStatus == 2) {
                        rejectedCount++;
                    }
                }
            }
            
            data.put("approvedContent", approvedCount);
            data.put("pendingReview", pendingCount);
            data.put("rejectedContent", rejectedCount);
            
            logger.debug("返回给前端的数据: approvedContent={}, pendingReview={}, rejectedContent={}", 
                approvedCount, pendingCount, rejectedCount);
            
            // 用户角色分布
            Map<String, Integer> roleCountMap = new HashMap<>();
            for (SysUser user : allUsers) {
                String role = user.getRole();
                roleCountMap.put(role, roleCountMap.getOrDefault(role, 0) + 1);
            }
            
            List<Map<String, Object>> roleDistribution = new ArrayList<>();
            Map<String, String> roleNameMap = new HashMap<>();
            roleNameMap.put("admin", "管理员");
            roleNameMap.put("teacher", "教师");
            roleNameMap.put("parent", "家长");
            roleNameMap.put("child", "学生");
            
            int totalUsersForDistribution = allUsers.size();
            for (Map.Entry<String, Integer> entry : roleCountMap.entrySet()) {
                Map<String, Object> roleStat = new HashMap<>();
                roleStat.put("role", entry.getKey());
                roleStat.put("roleName", roleNameMap.getOrDefault(entry.getKey(), entry.getKey()));
                roleStat.put("count", entry.getValue());
                roleStat.put("percentage", totalUsersForDistribution > 0 ? 
                    Math.round((entry.getValue() * 100.0 / totalUsersForDistribution)) : 0);
                roleDistribution.add(roleStat);
            }
            
            data.put("roleDistribution", roleDistribution);
            
            return R.ok("获取监控数据成功").data(data);
        } catch (Exception e) {
            System.err.println("获取监控数据失败: " + e.getMessage());
            e.printStackTrace();
            return R.error("获取监控数据失败: " + e.getMessage());
        }
    }
}